<?php
namespace Swork\Helper;

/**
 * 文件工具器
 * Class FileHelper
 * @package Swork\Helper
 */
class FileHelper
{
    /**
     * @param string $folder
     * @param bool $recursive
     * @param array $filter 只提取文件类型 如 ['php','img']
     * @return array
     */
    public static function files(string $folder, bool $recursive = false, array $filter = [])
    {
        $list = [];
        $sep = DIRECTORY_SEPARATOR;

        //后面强制加/
        if (substr($folder, -1, 1) != $sep)
        {
            $folder .= $sep;
        }

        //如果不是文件夹
        if (!is_dir($folder))
        {
            return $list;
        }

        //打开目录
        $dir = dir($folder);
        while (false !== ($entry = $dir->read()))
        {
            if ($entry !== '.' && $entry !== '..')
            {
                //检查是否包含子文件夹
                if (is_dir($dir->path . $sep . $entry) && $recursive)
                {
                    $next = self::files($folder, true, $filter);
                    $list = array_merge($list, $next);
                }

                //是否检查扩展名
                if (count($filter) > 0)
                {
                    $info = pathinfo($entry);
                    $ext = $info['extension'];
                    if (!in_array($ext, $filter))
                    {
                        continue;
                    }
                }

                //累加文件
                $list[] = $folder . $entry;
            }
        }

        //关闭目录
        $dir->close();

        //返回
        return $list;
    }
}
